#include <iostream>
#include <vector>
using namespace std;


//测试vector的默认扩容机制
void TestVectorExpand()
{
  size_t sz;
  vector<int> v;
  sz = v.capacity();
  cout<<"making v grow:\n";
  for(int i = 0;i<100;++i)
  {
    v.push_back(i);
    if(sz != v.capacity())
    {
      sz = v.capacity();
      cout<<"capacity changed: "<<sz<<endl;
    }
  }
}

// 如果已经确定vector中要存储元素大概个数，可以提前将空间设置足够
// 就可以避免边插入边扩容导致效率低下的问题了
void TestVectorExpandOP()
{
  vector<int> v;
  size_t sz = v.capacity();
  v.reserve(100); // 提前将容量设置好，可以避免一遍插入一遍扩容
  cout << "making bar grow:\n";
  for (int i = 0; i < 100; ++i)
  {
    v.push_back(i);
    if (sz != v.capacity())
    {
      sz = v.capacity();
      cout << "capacity changed: " << sz << '\n';
    }
  }
}

int main()
{
  vector<int> vv;
  vv.push_back(1);
  vv.push_back(2);
  vv.push_back(3);
  vv.push_back(4);
  //遍历vector
  
  //下标访问
  for(int i = 0;i<vv.size();++i)
  {
    cout<<vv[i]<<" ";
  }
  cout<<endl;
  
  //迭代器访问
  vector<int>::iterator it = vv.begin();
  while(it != vv.end())
  {
    cout<<*it<<" ";
    ++it;
  }
  cout<<endl;
  //范围for  范围for是C++11的语法，所以编译的时候要加上  -std=c++11
  for(auto e : vv)
  {
    cout<<e<<" ";
  }
  cout<<endl;

  TestVectorExpand(); 
  TestVectorExpandOP(); 
  
  return 0;
}
